import db from '../../config/sqlcfg';
import { isUndefined } from 'util';

class EthUserAddress {
  
  private static table: string = 'eth_user_address';

  /**
   * 获取用户eth地址列表(监听地址列表)
   * @returns
   * @memberof UserEthAddress
   */
  static async getUserEthAddressList() {
    let rows = await db.query(`select address from ${this.table} where address is not null`);
    return rows;
  }

  /**
   * 获取eth地址私钥
   * @param {string} address 以太坊地址
   * @returns {Promise<string>}
   * @memberof UserEthAddress
   */
  static async getUserAddressPrivateKey(address: string): Promise<string> {
    let rows = await db.query(`select privateKey from ${this.table} where address = ?`,[address]);
    if(isUndefined(rows[0])){
      await Promise.reject(`数据库[${this.table}]表中[${address}]字段数据不存在`);
    }
    return rows[0].privateKey;
  }

  /**
   * 保存用户地址
   * @param {(number|string)} uid 用户ID
   * @param {string} address 地址
   * @param {string} privateKey 私钥
   * @returns
   * @memberof UserEthAddress
   */
  static async saveUserAddress(uid: number|string, address: string, privateKey: string) {

    let row = await db.query(`select address from ${this.table} where uid = ${uid}`);

    if(!row.length){
      await db.query(`insert into ${this.table} 
        set 
          \`uid\` = ${uid},
          \`address\` = '${address}',
          \`privateKey\` = '${privateKey}'
      `);
    }else{
      return row[0].address;
    }
    return address;
  }
}

export default EthUserAddress;